package com.tinem.platform.service.task.consumer.redis;

import cn.hutool.core.util.StrUtil;
import com.baidu.fsg.uid.worker.dao.IdMappingRepository;
import com.baidu.fsg.uid.worker.entity.IdMapping;
import com.tinem.platform.module.pojo.co.RedisKeyEnum;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Configurable;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.dao.InvalidDataAccessApiUsageException;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import redis.clients.jedis.exceptions.JedisException;

import javax.annotation.Resource;
import java.util.NoSuchElementException;
import java.util.concurrent.TimeUnit;

@Slf4j
@Data
@Component
@Configurable
@ConfigurationProperties(prefix = "id.mapping.save.mysql")
public class IdMappingSaveToMySql implements ApplicationRunner {

    private int threadNum;

    @Resource
    StringRedisTemplate stringRedisTemplate;

    @Resource
    IdMappingRepository idMappingRepository;

    @Override
    public void run(ApplicationArguments args) throws Exception {
        for (int i = 0; i < threadNum; i++) {
            Thread thread = new Thread(()->{
                while (true){
                    try {
                        String id = stringRedisTemplate.opsForList().leftPop(RedisKeyEnum.id_mapping_query.getKey(),3600, TimeUnit.SECONDS);
                        if(StrUtil.isBlank(id)){
                            continue;
                        }
                        String uuid = stringRedisTemplate.opsForValue().get(RedisKeyEnum.id_uuid.getKey(id));
                        IdMapping idMapping = new IdMapping();
                        idMapping.setId(id);
                        idMapping.setUuid(uuid);
                        idMappingRepository.save(idMapping);
                    }catch (InvalidDataAccessApiUsageException e){
                        if(e.getCause() instanceof JedisException && e.getCause().getCause() instanceof NoSuchElementException){
                            //如果redis中没有数据，则睡眠60秒
                            try {
                                Thread.sleep(60*1000);
                            } catch (InterruptedException ex) {
                                ex.printStackTrace();
                            }
                        }else{
                            log.error("",e);
                        }
                    }catch (Exception e){
                        log.error("",e);
                    }

                }
            });
            thread.setName("idMappingSaveToMySql-"+i);
            thread.start();
        }

    }
}
